import { isArray, isObject } from '@/utils/types.js'

export default {
  methods: {
    /**
     * 格式化默认获取到的字段值
     * @param {Object} field
     */
    mixinsFormatFieldValue(field) {
      let value = field.value || field.defaultValue || ''
      if (['select', 'checkbox'].includes(field.formType)) {
        if (this.$isEmpty(value)) return []
        if (isArray(value)) {
          return value.map(o => {
            return isObject(o) ? o : { label: o, value: o }
          })
        } else {
          return value.split(',').map(o => {
            return { label: o, value: o }
          })
        }
      }
      switch (field.formType) {
        case 'single_user':
          if (this.$isEmpty(value)) return []
          if (!isArray(value)) return [value]
          return value
        case 'user':
          if (this.$isEmpty(value)) return []
          if (!isArray(value)) return [value]
          return value
        case 'contract':
          if (this.$isEmpty(value)) return []
          return value.map(o => {
            if (!o.hasOwnProperty('num')) {
              return {
                contractId: o.contractId,
                num: o.contractNum
              }
            } else {
              return o
            }
          })
        case 'receivables_plan':
          if (this.$isEmpty(value)) return []
          if (!isArray(value)) return [value]
          return value
        case 'date_interval':
          if (this.$isEmpty(value)) return []
          if (!isArray(value)) return []
          return value
        case 'detail_table':
          if (this.$isEmpty(field.value)) return []
          return value
      }
      return value
    },

    /**
     * 获取所有与逻辑表单相关字段的 formAssistId
     */
    getAllFormAssistId(fieldArr = []) {
      let ids = []
      for (let i = 0; i < fieldArr.length; i++) {
        const field = fieldArr[i]
        if (![
          'select',
          'checkbox'
        ].includes(field.formType)) continue
        if (field.remark !== 'options_type') continue
        ids.push(field.formAssistId)
        Object.keys(field.optionsData).forEach(key => {
          ids = ids.concat(field.optionsData[key])
        })
      }
      ids = ids.filter(o => Boolean(o))
      return Array.from(new Set(ids))
    }
  }
}
